from sqlalchemy.orm import Session
from models.payment_model import Payment
from schemas.payment_schemas import PaymentCreate, PaymentUpdate
from fastapi import HTTPException
from datetime import date
from models.user_models import Patient

def get_payment(db: Session, payment_id: int):
    db_payment = db.query(Payment).filter(Payment.ID == payment_id).first()
    if not db_payment:
        raise HTTPException(status_code=404, detail="Payment not found")
    return db_payment

def get_payments(db: Session, skip: int = 0, limit: int = 100):
    return db.query(Payment).offset(skip).limit(limit).all()

def create_payment(db: Session, payment: PaymentCreate):
    db_payment = Payment(
        patient_ID=payment.patient_ID,
        con_date=payment.con_date,
        expense=payment.expense,
        type=payment.type,
        pay_y_n=payment.pay_y_n,
        ref_ID=payment.ref_ID,
    )
    db.add(db_payment)
    db.commit()
    db.refresh(db_payment)
    return db_payment

def update_payment(db: Session, payment_id: int, payment: PaymentUpdate):
    db_payment = get_payment(db, payment_id)
    update_data = payment.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_payment, key, value)
    db.add(db_payment)
    db.commit()
    db.refresh(db_payment)
    return db_payment

def delete_payment(db: Session, payment_id: int):
    db_payment = get_payment(db, payment_id)
    db.delete(db_payment)
    db.commit()
    return {"message": "Payment deleted successfully"}

def get_payments_by_patient(db: Session, patient_id: int):
    """
    根据病人ID获取所有相关支付记录
    """
    return db.query(Payment).filter(Payment.patient_ID == patient_id).all()

def get_paid_payments_by_patient(db: Session, patient_id: int):
    """
    获取指定患者已支付的支付记录
    """
    return (
        db.query(Payment)
        .filter(Payment.patient_ID == patient_id, Payment.pay_y_n == 'Y')
        .all()
    )


def get_or_create_payment(db: Session, patient_id: int, con_date: date) -> Payment:
    """
    根据患者ID和日期查找或创建支付记录
    """
    try:
        # 先检查患者是否存在
        patient_exists = db.query(Patient).filter_by(ID=patient_id).first()
        if not patient_exists:
            raise HTTPException(status_code=404, detail="患者不存在")

        payment = db.query(Payment).filter_by(
            patient_ID=patient_id,
            con_date=con_date
        ).first()

        if not payment:
            payment = Payment(
                patient_ID=patient_id,
                con_date=con_date,
                expense=0,
                medi_expense=0,
                total_expense=0,
                pay_y_n='N'
            )
            db.add(payment)
            # 不在这里commit，由外层统一管理事务
        return payment
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=500,
            detail=f"支付记录操作失败: {str(e)}"
        )